/*
 * server-side-provider
 * Copyright (C) Ivan Surzhenko 2009 <i.surzhenko@gmail.com>
 * 
 * server-side-provider is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * server-side-provider is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
#include "server.h"

Server::Server(int port, RunMode mode) : Processor(mode)
{
	m_port = port;
}

void Server::Process()
{
	int * par = &m_port;
		short int port = *((int*)par);
	//port = 9999;
	LOG("Serve rThread")
	
	int       list_s;                /*  listening socket          */
    int       conn_s;                /*  connection socket         */
    //short int port;                  /*  port number               */
    struct    sockaddr_in servaddr;  /*  socket address structure  */
    //char     *endptr;                /*  for strtol()              */
	
	
	/*  Create the listening socket  */

    if ( (list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
    {
		LOG("ECHOSERV: Error creating listening socket.")
		return;
    }


    /*  Set all bytes in socket address structure to
        zero, and fill in the relevant data members   */

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(port);

	LOG(port);

    /*  Bind our socket addresss to the 
	listening socket, and call listen()  */

    if ( bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 )
    {
		LOG("ECHOSERV: Error calling bind()")
		return;
    }

    if ( listen(list_s, 1) < 0 )
    {
		LOG("ECHOSERV: Error calling listen()")
		return;
    }

    
    /*  Enter an infinite loop to respond
        to client requests and echo input  */

    while ( 1 ) {

	/*  Wait for a connection, then accept() it  */

	if ( (conn_s = accept(list_s, NULL, NULL) ) < 0 ) {
	    LOG("ECHOSERV: Error calling accept()")
	    return;
	}
	
	Connection * con = new Connection(conn_s, rm_Thread);
	con->Run();


    }
	return;
}
		
void Server::OnRun()
{
}

void Server::OnAfterRun()
{
}

void Server::OnStop()
{
}

void Server::OnAfterStop()
{
}